package com.supreme.uploadserver.service;

import com.alibaba.fastjson.JSONObject;
import com.sun.mail.util.BASE64DecoderStream;
import com.supreme.uploadserver.component.props.UploadServerProps;
import com.supreme.uploadserver.config.props.EmailSyncProps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class EmailService {

    @Value("${spring.mail.username}")
    private String mailFrom;

    @Resource
    private EmailSyncProps emailSyncProps;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private Store emailSyncStore;

    @Resource
    private MinioService minioService;

    @Resource
    private UploadServerProps uploadServerProps;

    public JSONObject test() {
        System.out.println(uploadServerProps.getProjectPath());
        System.out.println(uploadServerProps.getUploadPath());
        System.out.println(uploadServerProps.getTempPath());

        final Path path = Paths.get(uploadServerProps.getTempPath(), "a", "b", "abc.text");
        System.out.println(path);

        return new JSONObject() {{
            put("projectPath", uploadServerProps.getProjectPath());
            put("uploadPath", uploadServerProps.getUploadPath());
            put("tempData", uploadServerProps.getTempPath());
        }};
    }

    public List<JSONObject> emailSyncInboxFolder(Integer lastMessageCount) {
        List<JSONObject> mailList = new ArrayList<>();

        try {
            Folder folder = emailSyncStore.getFolder(emailSyncProps.getInbox());
            folder.open(Folder.READ_WRITE);

            int messageCount = folder.getMessageCount();
            int newMessageCount = folder.getNewMessageCount();
            int inboxStartPosition = (lastMessageCount > 0 ? messageCount - lastMessageCount : messageCount - newMessageCount) + 1;
            Message[] messageArray = folder.getMessages(inboxStartPosition, messageCount);

            for (Message message : messageArray) {
                MimeMessage mimeMessage = (MimeMessage) message;
                String contentType = mimeMessage.getContentType();
                String subject = mimeMessage.getSubject();
                Date sentDate = mimeMessage.getSentDate();

                final JSONObject jsonObject = new JSONObject() {{
                    put("subject", subject);
                    put("contentType", contentType);
                    put("sentDate", sentDate);
                }};

                Object messageContent = mimeMessage.getContent();
                if (messageContent instanceof MimeMultipart) {
                    MimeMultipart mimeMultipartContent = (MimeMultipart) messageContent;

                    final int contentCount = mimeMultipartContent.getCount();
                    for (int i = 0; i < contentCount; i++) {
                        final BodyPart contentBodyPart = mimeMultipartContent.getBodyPart(i);

                        final Object lv2Content = contentBodyPart.getContent();
                        if (lv2Content instanceof String) {
//                            System.out.println("lv2Content: " + lv2Content);
                            jsonObject.put("mainBody", lv2Content);
                        } else if (lv2Content instanceof BASE64DecoderStream) {
                            String bodyPartFileName = contentBodyPart.getFileName();
                            bodyPartFileName = MimeUtility.decodeText(bodyPartFileName);

                            String bodyPartContentType = contentBodyPart.getContentType();
                            bodyPartContentType = StringUtils.substringBefore(bodyPartContentType, ";");
                            int bodyPartSize = contentBodyPart.getSize();

                            System.out.println("bodyPartFileName: " + bodyPartFileName);
                            System.out.println("bodyPartContentType: " + bodyPartContentType);
                            System.out.println("bodyPartSize: " + bodyPartSize);
                            jsonObject.put(bodyPartContentType, bodyPartFileName);

                            BASE64DecoderStream base64DecoderStream = (BASE64DecoderStream) lv2Content;
                            byte[] copyToByteArray = FileCopyUtils.copyToByteArray(base64DecoderStream);

                            Path writeFilePath = Paths.get(uploadServerProps.getTempPath(), bodyPartFileName);
                            File writeFile = writeFilePath.toFile();
                            FileCopyUtils.copy(copyToByteArray, writeFile);

//                            minioService.upload(uploadServerProps.getMinioBucket(), bodyPartFileName, writeFilePath.toString(), bodyPartContentType);
                        }
                    }
                } else if (messageContent instanceof String) {
                    System.out.println("messageContent: " + messageContent);
                    jsonObject.put("mainBody", messageContent);
                }

                mailList.add(jsonObject);
            }

            folder.close();
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }

        return mailList;
    }

    public void sendCopyMessage(MimeMessage mimeMessage, String fromAddress, String toAddress) {
        try {
            MimeMessage sendMessage = javaMailSender.createMimeMessage();
            sendMessage.setFrom(new InternetAddress(fromAddress));
            sendMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            sendMessage.setSubject(mimeMessage.getSubject() + " - " + LocalDateTime.now());
            sendMessage.setContent(mimeMessage.getContent(), mimeMessage.getContentType());
            sendMessage.setSentDate(new Date());
            javaMailSender.send(sendMessage);
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送文本邮件
     * @param mailTo 收件人邮箱地址
     * @param subject 主题
     * @param content 内容
     */
    public void sendTextMail(String mailTo, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(mailTo);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(mailFrom);
        javaMailSender.send(simpleMailMessage);
    }

    /**
     * 发送html内容的邮件
     * @param mailTo 收件人
     * @param htmlContent html内容
     * @param subject 主题
     * @throws MessagingException
     */
    public void sendHtmlMail(String mailTo, String subject, String htmlContent) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setTo(mailTo);
        messageHelper.setSubject(subject);
        messageHelper.setFrom(mailFrom);
        messageHelper.setText(htmlContent, true);
        javaMailSender.send(message);
    }

    /**
     * 发送图文邮件
     * @param mailTo 收件人
     * @param imgContent 图文内容
     * @param subject 主题
     * @param rscId 资源id
     * @param imgPath 资源路径
     * @throws MessagingException
     */
    public void sendImgMail(String mailTo, String imgContent, String subject, String rscId, String imgPath) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setTo(mailTo);
        messageHelper.setSubject(subject);
        messageHelper.setFrom(mailFrom);
        messageHelper.setText(imgContent, true);
        messageHelper.addInline(rscId, new File(imgPath));
        javaMailSender.send(message);
    }
}
